package com.befiv.lock.redis;

import com.befiv.lock.redis.exception.UnableToAquireLockException;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.TimeUnit;

/**
 * @Author: Gjq
 * @Date: 2019/3/25 0025 下午 5:51
 */
public class RedisLocker implements DistributedLocker {
    private final static String LOCKER_PREFIX = "lock:";
    @Autowired
    RedissonConf redissonConf;
    @Override
    public Object lock(String resourceName, AquiredLockWorker worker) throws UnableToAquireLockException, Exception {
        //设置n秒自动释放锁
        return lock(resourceName,worker,10,100);
    }
    @Override
    public Object lock(String resourceName, AquiredLockWorker worker, long lockTime,long timeout) throws UnableToAquireLockException, Exception {
        RedissonClient redisson= redissonConf.getClient();
        RLock lock = redisson.getLock(LOCKER_PREFIX + resourceName);
        //l:获取锁的最大等待时间 如果超过这个时间就抛出异常
        boolean success = lock.tryLock(timeout, lockTime, TimeUnit.SECONDS);
        if (success) {
            try {
                return worker.invokeAfterLockAquire();
            } finally {
                lock.unlock();
            }
        }
        throw new UnableToAquireLockException("等待时间超时...");
    }
}

